package com.heima.leetcode.practice;

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;

/**
 * @description: leetcode 102 二叉树的层序遍历
 * @author 勾新杰
 * @version 1.0
 * @date 2025/1/9 11:15
 */
public class E102 {

    /**
     * <h3>方法一：正常的层序遍历</h3>
     * @param root 根节点
     * @return 遍历结果
     */
    @SuppressWarnings("all")
    public List<List<Integer>> levelOrder(TreeNode root) {
        List<List<Integer>> result = new ArrayList<>();
        LinkedList<TreeNode> queue = new LinkedList<>();
        if (root == null) return result;
        queue.offer(root);
        while (!queue.isEmpty()){
            int size = queue.size();
            List<Integer> level = new ArrayList<>();
            for (int i = 0; i < size; i++){
                TreeNode poll = queue.poll();
                level.add(poll.val);
                if (poll.left != null)
                    queue.offer(poll.left);
                if (poll.right != null)
                    queue.offer(poll.right);
            }
            result.add(level);
        }
        return result;
    }
}
